<template>
  <div class="app-container">
    <el-form
      ref="dataForm"
      :rules="rules"
      :model="postForm"
      label-position="right"
      label-width="100px"
      style="width: 400px; margin-left:50px;"
    >
        <el-input v-model="postForm.username" :disabled="isEdit" clearable placeholder="请输入账号"
                  @keyup.native="validUsername" maxlength="30"/>
      </el-form-item>
      <el-form-item label="姓名" prop="realName">
        <el-input v-model="postForm.realName" clearable placeholder="请输入姓名" maxlength="10"/>
      </el-form-item>
      <el-form-item v-if="!isManager" label="手机号" prop="mobile">
        <el-input v-model="postForm.mobile" clearable placeholder="请输入手机号" maxlength="11"
                  style="display: inline-block;width: 61%"/>
        <el-button :disabled="isManager || postForm.mobile === postForm.oldMobile || sendStatus === 1" v-waves clearable
                   class="filter-item" style="width: 37%" type="warning" @click="getMessage"><span
          id="btnText">获取验证码</span></el-button>
        <span id="showCount" style="color: white; display: none">{{ countt }}s</span>
      </el-form-item>
      <el-form-item v-if="!isEdit" label="手机号" prop="mobile">
        <el-input v-model="postForm.mobile" clearable placeholder="请输入手机号" maxlength="11"
                  style="display: inline-block;"/>
      </el-form-item>
      <el-form-item v-if="!isManager && postForm.mobile!==postForm.oldMobile" label="验证码" prop="code">
        <el-input v-model="postForm.code" placeholder="请输入验证码" maxlength="6" @keyup.native="changeCircle"/>
        <span class="show-pwd-default" v-if="circleFlag">
          <!--<el-button :type="circleType" :icon="circleIcon" circle></el-button>-->
          <i :style="circleType" :class="circleIcon"></i>
        </span>
      </el-form-item>
      <el-form-item label="座机号" prop="telephone">
        <el-input v-model="postForm.telephone" clearable placeholder="请输入座机号" maxlength="11"/>
      </el-form-item>
      <el-form-item label="身份证号" prop="idcard">
        <el-input v-model="postForm.idcard" clearable placeholder="请输入身份证号" maxlength="20"/>
      </el-form-item>
      <el-form-item label="工作证号" prop="workcard">
        <el-input v-model="postForm.workcard" clearable placeholder="请输入工作证号" maxlength="30"/>
      </el-form-item>
      <el-form-item label="岗位" prop="position">
        <el-input v-model="postForm.position" clearable placeholder="请输入岗位" maxlength="50"/>
      </el-form-item>
      <el-form-item v-if="isManager && isAdmin" label="角色" prop="roleIdAry" :disabled="false">
        <el-select v-model="postForm.roleIdAry" multiple filterable placeholder="请选择" style="width: 100%;">
          <el-option
            v-for="item in allRoles"
            :key="item.id"
            :label="item.roleName"
            :value="item.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="描述" prop="remark">
        <el-input
          v-model="postForm.remark"
          :autosize="{ minRows: 2, maxRows: 4}"
          type="textarea"
          placeholder="描述"
          maxlength="200"
        />
      </el-form-item>
      <el-form-item>
        <el-button v-waves @click="$router.back()">返回</el-button>
        <el-button v-waves type="primary" @click="submitForm">确定</el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script>
import { saveUser, updateUser, getUser, validateUsername, getValidateCode, validateMobile, validateIdCard } from '@/api/system/user'
import { getRolesByUserAndSystem } from '@/api/system/role'
import { getUserId, setUser } from '@/utils/auth'
import waves from '@/directive/waves' // waves directive
import { validMobile, validIdcard } from '@/utils/validate'

const defaultForm = {
  id: null,
  username: null,
  realName: null,
  telephone: null,
  mobile: null,
  idcard: null,
  workcard: null,
  position: null,
  roleIds: null,
  roleIdAry: null,
  oldMobile: null,
  code: null,
  remark: null,
  createdBy: getUserId()
}

export default {
  name: 'UserDetail',
  directives: { waves },
  props: {
    isEdit: {
      type: Boolean,
      default: false
    },
    isManager: {
      type: Boolean,
      default: true
    }
  },
  data() {
    const validateUsername = (rule, value, callback) => {
      if (value === null || value.trim() === '') {
        callback(new Error('用户名不能为空'))
      } else {
        if (!this.isEdit) {
          this.checkUsername(value, callback, rule)
        } else {
          callback()
        }
      }
    }
    const validateCode = (rule, value, callback) => {
      if (value === null || value.trim() === '') {
        callback(new Error('验证码不能为空'))
      } else {
        callback()
      }
    }
    const validateIdcard = (rule, value, callback) => {
      if (!validIdcard(value)) {
        callback(new Error('身份证号格式不正确'))
      } else {
        if (this.oldIdCard !== value) {
          this.checkIdCard(value, callback, rule)
        } else {
          callback()
        }
      }
    }
    const validateMobileVal = (rule, value, callback) => {
      if (!validMobile(value)) {
        this.sendStatus = 1
        callback(new Error('手机号格式不正确'))
      } else {
        if (this.postForm.oldMobile !== value) {
          this.checkMobile(value, callback, rule)
        } else {
          callback()
        }
      }
    }
    return {
      loading: true,
      postForm: Object.assign({}, defaultForm),
      allRoles: [],
      sendStatus: 0,
      isAdmin: false,
      circleFlag: false,
      circleType: '',
      circleIcon: '',
      oldIdCard: null,
      editCheckId: null,
      authSystemId: null,
      countt: 60,
      timer: null,
      rules: {
        username: [
          { required: true, trigger: 'change', validator: validateUsername },
          { min: 1, max: 20, message: '长度在 1 到 15 个字符', trigger: 'change' }
        ],
        realName: [
          { required: true, message: '姓名不能为空', trigger: 'change' },
          { min: 1, max: 20, message: '长度在 1 到 30 个字符', trigger: 'change' }
        ],
        mobile: [
          { required: true, validator: validateMobileVal, trigger: 'change' }
        ],
        status: [
          { required: true, message: '状态不能为空', trigger: 'change' }
        ],
        roleIdAry: [
          { required: true, message: '角色不能为空', trigger: 'change' }
        ],
        code: [{ required: true, trigger: 'change', validator: validateCode }],
        idcard: [{ required: true, trigger: 'change', validator: validateIdcard }]
      },
      treeData: []
    }
  },
  watch: {
    filterText(val) {
      this.$refs.tree.filter(val)
    }
  },
  mounted() {
    // this.getDepartmentTree()
  },
  beforeDestroy() {
    clearInterval(this.timer)
  },
  created() {
    if (getUserId() === '23') {
      this.isAdmin = true
    }
    this.ljOptions = ljOptions()
    this.selectSystemList()
  },
  methods: {
    getRoleList() {
      if (this.isManager) {
        getRolesByUserAndSystem({userId: getUserId(), authSystemId: this.authSystemId}).then(response => {
          this.allRoles = response.data.list
          if (!this.isEdit) {
            const roleIds = []
            roleIds.push(Number(response.data.default))
            this.postForm.roleIds = roleIds
            this.postForm.roleIdAry = roleIds
          }
        })
      }
    },
    showResource(authSystemId) {
      this.authSystemId = authSystemId
      this.getRoleList()
      // this.getDepartmentTree()
    },
    checkMobile(mobile, callback, rule) {
      validateMobile({mobile: mobile}).then(response => {
        const returnCode = response && response.returnCode
        if (returnCode !== this.Const.OK) {
          this.sendStatus = 1
          callback(new Error(response.msg))
        } else {
          this.sendStatus = 0
          callback()
        }
      })
    },
    checkIdCard(idCard, callback, rule) {
      validateIdCard({idCard: idCard}).then(response => {
        const returnCode = response && response.returnCode
        if (returnCode !== this.Const.OK) {
          callback(new Error(response.msg))
        } else {
          callback()
        }
      })
    },
    setTime() {
      this.countt--
      if (this.countt < 1) {
        this.showSend()
      }
    },
    getMessage() {
      const value = this.postForm.mobile
      if (validMobile(value)) {
        this.timer = setInterval(this.setTime, 1000)
        this.showCount()
        getValidateCode({mobile: value}).then(response => {
          if (this.Const.OK === response.returnCode) {
            this.$message({
              type: 'success',
              message: '获取验证码成功'
            })
          } else {
            this.$message({
              type: 'error',
              message: response && response.msg || '验证失败'
            })
            this.showSend()
          }
        }).catch(() => {
          this.$message({
            type: 'error',
            message: '获取验证码失败'
          })
          this.showSend()
        })
      }
    },
    setTime() {
      this.countt--
      if (this.countt < 1) {
        this.countt = 60
        this.showSend()
      } else {
        this.showCount()
      }
    },
    showSend() {
      document.getElementById('btnText').innerHTML = '获取验证码'
      this.sendStatus = 0
      clearInterval(this.timer)
    },
    showCount() {
      document.getElementById('btnText').innerHTML = this.countt + 's'
      this.sendStatus = 1
    },

    fetchData(id) {
      const roleIds = []
      getUser({ id: id }).then(response => {
        this.postForm = Object.assign(this.postForm, response.data)
        this.oldIdCard = response.data.idcard
        const sysRoles = response.data && response.data.roleIds
        if (sysRoles) {
          sysRoles.split('@').forEach(roleId => {
            if (roleId !== '') {
              roleIds.push(Number(roleId))
            }
          })
        }
        this.postForm.roleIds = roleIds
        this.postForm.roleIdAry = roleIds
        this.loading = false
        this.authSystemId = response.data.authSystemId
        this.getRoleList()
      })
    },
    checkUsername(username, callback, rule) {
      validateUsername({username: username}).then(response => {
        const returnCode = response && response.returnCode
        if (returnCode !== this.Const.OK) {
          callback(new Error(response.msg))
        } else {
          callback()
        }
      })
    },
    submitForm() {
      this.$refs.dataForm.validate(valid => {
        if (valid) {
          setUser(this.postForm.realName)
          this.postForm.roleIds = this.postForm.roleIdAry.join('@')
          if (this.isEdit) {
            updateUser(this.postForm).then(response => {
              const returnCode = response && response.returnCode
              if (this.Const.OK === returnCode) {
                this.$message({
                  type: 'success',
                  message: '更新成功'
                })
                this.$router.back()
              } else {
                this.$message({
                  type: 'error',
                  message: response && response.msg || '更新失败'
                })
              }
            })
          } else {
            this.postForm.authSystemId = this.authSystemId
            saveUser(this.postForm).then(response => {
              const returnCode = response && response.returnCode
              if (this.Const.OK === returnCode) {
                this.$message({
                  type: 'success',
                  message: '保存成功'
                })
                this.$router.back()
              } else {
                this.$message({
                  type: 'error',
                  message: response && response.msg || '保存失败'
                })
              }
            }).catch(() => {
              this.$message({
                type: 'error',
                message: '保存失败'
              })
            })
          }
        }
      })
    },
    validUsername() {
      this.postForm.username = this.postForm.username.replace(/[^\w]/g, '')
    }
  }
}
</script>
<style>
  .info-department .el-select {
    width: 100%;
  }

</style>
<style lang="scss" scoped>
  .show-pwd {
    position: absolute;
    right: 10px;
    top: 7px;
    font-size: 16px;
    color: #eee;
    cursor: pointer;
    user-select: none;
  }
  .show-pwd-default {
    position: absolute;
    right: 10px;
    top: 1px;
    font-size: 16px;
    color: #889aa4;
    cursor: pointer;
    user-select: none;
  }
</style>
